package unit9;

import java.sql.Connection;
import java.sql.DriverManager;

public class Ex9_2_Example9_2 {
    private static final String DRIVER = "com.mysql.jdbc.Driver";
    private static final String URL = "jdbc:mysql://localhost:3306/student";
    private static final String UNAME = "root";
    private static final String UPWD = "123456";
    private Connection conn = null;
    //创建一个数据库连接
    public Connection getConnection() {
        try {
            Class.forName(DRIVER);
            conn = DriverManager.getConnection(URL, UNAME, UPWD);
            if (conn != null)
                System.out.println("连接数据库成功！");
        } catch (Exception e) {
            System.out.println("连接数据库失败：" + e.getMessage());
        }
        return conn;
    }
    // 关闭连接
    public void closeConnection() {
        try {
            if (conn != null)
                conn.close();
            conn = null;
            System.out.println("数据库连接关闭成功！");
        } catch (Exception e) {
            System.out.println("数据库连接关闭失败：" + e.getMessage());
        }
    }
//主方法
    public static void main(String[] args) {
        Ex9_2_Example9_2 dbcon = new Ex9_2_Example9_2();
        Connection con = dbcon.getConnection();
        dbcon.closeConnection();
    }
}
